package org.bapoint.bawirelessprogressordercenter.service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.annotation.Resource;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.bapoint.bawirelessprogressordercenter.config.RedisConfig;
import org.bapoint.bawirelessprogressordercenter.mapper.GetFromDbMapper;
import org.bapoint.bawirelessprogressordercenter.service.GetFromDbService;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName GetFromDbServiceImpl
 * @Description TODO
 * @Author 王逸攀
 * @Date 2025/9/7 16:14
 * @Version 1.0
 */
@Service
public class GetFromDbServiceImpl implements GetFromDbService {

    @Resource
    private GetFromDbMapper getFromDbMapper;

    @Resource
    private RedisConfig redisConfig;

    private static final Log LOGGER = LogFactory.getLog(GetFromDbServiceImpl.class);


    @Override
    public List<Map<String, Object>> getRedisDb() throws JsonProcessingException {
        ObjectMapper objectMapper = new ObjectMapper();
        RedisTemplate<String, Object> db5 = redisConfig.getRedisTemplateByDb(5);
        String redisList = (String)db5.opsForValue().get("list");
        if (redisList!=null){
            LOGGER.info("读取缓存成功！");
            return objectMapper.readValue(redisList, new TypeReference<>() {});
        }
        List<Map<String, Object>> list = getFromDbMapper.list();
        String jsonList = objectMapper.writeValueAsString(list);
        db5.opsForValue().set("list",jsonList);
        db5.expire("list",100, TimeUnit.SECONDS);
        LOGGER.error("读取缓存失败！");
        return list;
    }
}
